package com.walker.kuyun.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.walker.kuyun.App
import com.walker.kuyun.bean.SearchHistoryBean
import com.walker.kuyun.database.converter.DownloadStatusConverter
import com.walker.kuyun.database.converter.ImageBeanConverter
import com.walker.kuyun.database.dao.DownloadDao
import com.walker.kuyun.database.dao.FavoriteTMDao
import com.walker.kuyun.database.dao.SearchHistoryDao
import com.walker.kuyun.database.entity.DownloadEntity
import com.walker.kuyun.bean.FavoriteTMBean
import com.walker.kuyun.bean.HistoryBean
import com.walker.kuyun.database.dao.HistoryDao
import java.util.HashSet

@Database(
    entities = [SearchHistoryBean::class,
        DownloadEntity::class,
        FavoriteTMBean::class,
        HistoryBean::class], version = 3
)
@TypeConverters(
    value = [DownloadStatusConverter::class,
        ImageBeanConverter::class]
)
abstract class AppDatabase : RoomDatabase() {

    abstract fun searchHistoryDao(): SearchHistoryDao
    abstract fun animeDownloadDao(): DownloadDao
    abstract fun favoriteAnimeDao(): FavoriteTMDao
    abstract fun historyDao(): HistoryDao

    companion object {
        private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            if (instance == null) {
                if (instance != null) return instance as AppDatabase
                return synchronized(this) {
                    Room.databaseBuilder(
                        context.applicationContext,
                        AppDatabase::class.java,
                        "app.db"
                    )
                        .build()
                }
            } else {
                return instance as AppDatabase
            }

        }
    }

    interface DBCallback<T> {
        fun success(result: T)
        fun fail(throwable: Throwable)
    }
}

fun getAppDataBase() = AppDatabase.getInstance(App.getApp())